/**
 * Created by ren on 10/04/2017.
 */
import React, {Component} from 'react';
import {
  StyleSheet,
  Platform,
  Image,
  Dimensions,
  StatusBar,
  TouchableWithoutFeedback
}from 'react-native';
import {Container, Content, Text, List, ListItem, Left, Icon, Body, Right, Button, Header, Title} from 'native-base'
import {getSize} from '../../utils/response'
import Picker from 'react-native-picker';
import PageUtil from '../../utils/PageUtil'
import NamePage from './NamePage'
import * as api from '../../utils/api'
import * as Netservice from '../../utils/netservice'
import * as type from '../../actions'
import {connect} from 'react-redux'

class Information extends Component {
  constructor(props, context) {
    super(props, context);
    this.PageUtil = new PageUtil()
    this.state = {
      birthday: "2016-05-15",
      sex: '男',
      nickName: '万小颗',
      modalVisible: true
    }
  }

  componentDidMount() {
    const {nickName, sex, birthday} =this.props;
    this.setState({
      nickName: nickName,
      sex: sex === "1" ? '男' : '女',
      birthday: birthday ? birthday.substring(0, 11) : ''
    })
  }

  componentWillUnmount() {
    Picker.hide()
  }

  _createDateData() {
    let date = [];
    for (let i = 1950; i < new Date().getFullYear() + 1; i++) {
      let month = [];
      for (let j = 1; j < 13; j++) {
        let day = [];
        if (j === 2) {
          for (let k = 1; k < 29; k++) {
            day.push(k);
          }
          //Leap day for years that are divisible by 4, such as 2000, 2004
          if (i % 4 === 0) {
            day.push(29);
          }
        }
        else if (j in {1: 1, 3: 1, 5: 1, 7: 1, 8: 1, 10: 1, 12: 1}) {
          for (let k = 1; k < 32; k++) {
            day.push(k);
          }
        }
        else {
          for (let k = 1; k < 31; k++) {
            day.push(k);
          }
        }
        let _month = {};
        _month[j] = day;
        month.push(_month);
      }
      let _date = {};
      _date[i] = month;
      date.push(_date);
    }
    return date;
  }


  _showDatePicker() {
    let newDate = new Date()
    let birthdayArray = this.state.birthday ? (this.state.birthday).split('-') : [newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate()]
    Picker.init({
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      pickerTitleText: '请选择生日',
      pickerData: this._createDateData(),
      pickerToolBarFontSize: 16,
      pickerFontSize: 16,
      selectedValue: [parseInt(birthdayArray[0]), parseInt(birthdayArray[1]), parseInt(birthdayArray[2])],
      pickerFontColor: [0, 0, 0, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
        this.setState({
          birthday: pickedValue[0] + '-' + pickedValue[1] + '-' + pickedValue[2]
        })
        storage.load({
          key: 'loginState'
        }).then(ret => {
          let id = ret.id
          Netservice.post(api.modifyBus, {
            id: id,
            birthday: this.state.birthday
          }).then(response => {
            const {dispatch}=this.props
            dispatch(type.updateBirthday(this.state.birthday))
            Netservice.toast('修改成功！')
          })
        }).catch(err => {
          console.log(err)
        })
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }

  _showGenderPicker() {
    const {sex} =this.props;
    Picker.init({
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      pickerTitleText: '请选择性别',
      pickerData: ['男', '女'],
      pickerToolBarFontSize: 16,
      pickerFontSize: 16,
      selectedValue: [sex],
      pickerFontColor: [0, 0, 0, 1],
      onPickerConfirm: (pickedValue, pickedIndex) => {
        this.setState({
          sex: pickedValue[0]
        })
        storage.load({
          key: 'loginState'
        }).then(ret => {
          let id = ret.id
          const {dispatch}=this.props
          Netservice.post(api.modifyBus, {
            id: id,
            sex: this.state.sex === '男' ? "1" : "2"
          }).then(response => {
            dispatch(type.updateSex(this.state.sex))
            Netservice.toast('修改成功！')
          })
        }).catch(err => {
          console.log(err)
        })
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      }
    });
    Picker.show();
  }

  render() {
    const {nickName}=this.props;
    return (
      <Container style={{backgroundColor:'#F4F4F4'}}>
        <Header iosBarStyle="light-content" backgroundColor="#16BD42"
                style={{backgroundColor:'#16BD42',height:Platform.OS==='ios'?getSize(64):getSize(50),borderBottomWidth:0,marginBottom:getSize(7)}}>
          <StatusBar
            backgroundColor={'#303135'}
          />
          <Left style={{flex:1}}>
            <Button transparent onPress={this.PageUtil.pop}>
              <Icon name='arrow-back' style={{fontSize:getSize(24),color:'white'}}/>
            </Button>
          </Left>
          <Body style={{alignItems:'center'}}>
          <Title style={{color:'white',fontSize:getSize(19)}}>基本信息</Title>
          </Body>
          <Right style={{flex:1}}>
            <Button transparent>
            </Button>
          </Right>
        </Header>
        <Content>
          <List style={{backgroundColor:'white'}}>
            <TouchableWithoutFeedback
              onPress={()=>this.PageUtil.jumpPageWithComponent(NamePage)}>
              <ListItem style={{borderBottomWidth:getSize(10),borderBottomColor:'#F4F4F4'}} last>
                <Left>
                  <Text style={styles.text}>昵称</Text>
                </Left>
                <Right style={styles.rightBtn}>
                  <Text note style={styles.rightBtnText}>{nickName}</Text>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={this._showGenderPicker.bind(this)}>
              <ListItem>
                <Left>
                  <Text style={styles.text}>性别</Text>
                </Left>
                <Right style={styles.rightBtn}>
                  <Text note style={styles.rightBtnText}>{this.state.sex}</Text>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback onPress={this._showDatePicker.bind(this)}>
              <ListItem>
                <Left>
                  <Text style={styles.text}>生日</Text>
                </Left>
                <Right style={styles.rightBtn}>
                  <Text note style={styles.rightBtnText}>{this.state.birthday}</Text>
                  <Icon name={'ios-arrow-forward'}/>
                </Right>
              </ListItem>
            </TouchableWithoutFeedback>
          </List>
        </Content>
      </Container>
    )
  }
}
function select(store) {
  return {
    nickName: store.routesStore.updateNickName,
    sex: store.routesStore.updateSex,
    birthday: store.routesStore.updateBirthday
  }
}
export default connect(select)(Information)
const styles = {
  text: {
    color: '#696969',
    fontSize: getSize(16)
  },
  rightBtn: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end'
  },
  rightBtnText: {
    marginRight: getSize(10)
  }
}